﻿//------------------------------------------------------------------
// System Name:    smsGateway
// Component:      Web
// Create by:      Evans Liao (evansl@wicresoft.com)
// Create Date:    2011-01-03
//------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.SMS.Common;
using Wicresoft.SMS.Data;

namespace Wicresoft.SMS.Web.Controllers
{
    public class ManageController : CustomBaseController
    {
        //
        // GET: /Manage/

        public ActionResult Index()
        {
            return View();
        }

        public ViewResult Group(string category)
        {
            if (string.Equals(category, "edit", StringComparison.OrdinalIgnoreCase))
                return GroupEdit();
            return GroupCreate();
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult Users(ManageModel model)
        {
            if (string.Equals(model.category, "group", StringComparison.OrdinalIgnoreCase))
                //return GroupUsers();
                return UserCreate(model);
            else if (string.Equals(model.category, "company", StringComparison.OrdinalIgnoreCase))
                return CompanyUsers(model);
            else if (string.Equals(model.category, "new", StringComparison.OrdinalIgnoreCase))
                return PendingList(model);
            else if (string.Equals(model.category, "exportusers", StringComparison.OrdinalIgnoreCase))
                return ExportUsers();

            return UserCreate(model);
        }

        #region 不要的

        private ViewResult GroupCreate()
        {
            return View("GroupCreate");
        }

        private ViewResult GroupEdit()
        {
            return View("GroupEdit");
        }

        private ViewResult GroupUsers()
        {
            return View("GroupUsers");
        }

        #endregion

        private ActionResult UserCreate(ManageModel model)
        {
            if (model.id != 0)
            {
                WebConfigProvider wcp = new WebConfigProvider();
                IUserService iu = new UserService(wcp);

                model.aliasemail = iu.GetUserItemByID(model.id).CIL + ";";

                return View("UserCreate", model);
            }
            if (model.aliasemail != null)
            {
                // bool isactive = model.isactive != null ? true : false;
                bool isadmin = model.isgroupadmin[0] == "yes" ? true : false;

                string[] userarry = model.aliasemail.Split(';');
                var list = userarry.ToList();
                List<string> userlist = new List<string>();
                foreach (var item in list)
                {
                    if (item.Trim() != "")
                        userlist.Add(item);
                }
                string[] newusers = userlist.ToArray();
                WebConfigProvider wcp = new WebConfigProvider();
                IUserService iu = new UserService(wcp);
                ICILHelper cil = new CILHelper("", wcp.HRConnectionString);
                var cilusers = cil.GetUserInfosByCILArray(model.aliasemail.Split(';'));
                if (iu.CreateOrUpdateUser(cilusers, true, isadmin))
                {
                    model.Msg="";
                    model.aliasemail = "";

                    foreach (var item in cilusers)
                    {
                        model.Msg += item.CILX500 + ";";
                    }
                    model.Msg += App_GlobalResources.Resources.Controller_Manageuser_Success;
                }

                var failed = GetFailedUsers(cilusers, newusers);
                if (failed.Count() != 0)
                {
                    model.ErrorMsg = "";
                    model.aliasemail = "";

                    foreach (var item in failed)
                    {
                        model.ErrorMsg += item + ";";
                        model.aliasemail += item + ";";
                    }
                    model.ErrorMsg += App_GlobalResources.Resources.Controller_Manageuser_CILError;

                }
                return View("UserCreate", model);
            }

            return View("UserCreate", model);
        }

        private string[] GetFailedUsers(C_evw_Employee[] result, string[] source)
        {
            List<string> list = new List<string>();
            foreach (var item in source)
            {
                var temp = result.FirstOrDefault(a => a.CILX500.ToLower() == item.ToLower());
                if (temp == null)
                    list.Add(item);
            }
            return list.ToArray();
        }

        private ActionResult CompanyUsers(ManageModel model)
        {
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);
            model.list = us.GetAllUsers(model.page, max, model.key);
            model.maxpages = us.GetPageCount(max, model.key);
            model.IsChangeUrl = true;
            return View("CompanyUsers", model);
        }

        private ActionResult PendingList(ManageModel model)
        {
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);
            model.list = us.GetAllUsers(model.page, max, model.key, true);
            model.maxpages = us.GetPageCount(max, model.key, true);
            model.IsChangeUrl = true;
            return View("PendingList", model);
        }

        [HttpPost]
        public ActionResult ActiveOrUnactiveUsers(string[] items, string todo, ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);
            todo = todo.Trim();
            if (todo == "激活" || todo=="Activate")
                us.ActiveUsers(true, items);
            else
                us.ActiveUsers(false, items);

           // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key);
            model.maxpages = us.GetPageCount(max, model.key);
            model.IsChangeUrl = false;

            return View("HistoryGrid", model);
        }

        [HttpPost]
        public ActionResult ActiveUser(ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);

            string[] ids = new string[1];
            ids[0] = model.id.ToString();

            us.ActiveUsers(true, ids);

           // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key);
            model.maxpages = us.GetPageCount(max, model.key);
            model.IsChangeUrl = false;

            return View("HistoryGrid", model);
        }

        [HttpPost]
        public ActionResult UnActiveUser(ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);

            string[] ids = new string[1];
            ids[0] = model.id.ToString();

            us.ActiveUsers(false, ids);

           // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key);
            model.maxpages = us.GetPageCount(max, model.key);
            model.IsChangeUrl = false;

            return View("HistoryGrid", model);
        }

        [HttpPost]
        public ActionResult AllowOrRefuseUsers(string[] items, string todo, ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);
            todo = todo.Trim();
            if (todo == "批准" || todo == "Approve")
                us.AllowUsers(true, items);
            else
                us.AllowUsers(false, items);

            // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key, true);
            model.maxpages = us.GetPageCount(max, model.key, true);
            model.IsChangeUrl = false;

            return View("datagrid", model);
        }

        [HttpPost]
        public ActionResult AllowUser(ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);

            string[] ids = new string[1];
            ids[0] = model.id.ToString();

            us.AllowUsers(true, ids);

            // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key, true);
            model.maxpages = us.GetPageCount(max, model.key, true);
            model.IsChangeUrl = false;

            return View("datagrid", model);
        }

        [HttpPost]
        public ActionResult RefuseUser(ManageModel model)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            int max = Convert.ToInt32(wcp.MaxshowInHistory);
            IUserService us = new UserService(wcp);

            string[] ids = new string[1];
            ids[0] = model.id.ToString();

            us.AllowUsers(false, ids);

            // ManageModel model = new ManageModel();
            if (model.page == 0)
                model.page = 1;
            if (model.key == null)
                model.key = "";
            model.list = us.GetAllUsers(model.page, max, model.key, true);
            model.maxpages = us.GetPageCount(max, model.key, true);
            model.IsChangeUrl = false;

            return View("datagrid", model);
        }

        public ActionResult ExportUsers()
        {
            WebConfigProvider wcp = new WebConfigProvider();
            IUserService us = new UserService(wcp);
            System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();
            gv.DataSource = us.GetAllUsers(false);
            gv.DataBind();

            //代码来源 http://blog.csdn.net/zhoufoxcn/archive/2008/05/16/2450642.aspx
            Response.Clear();
            Response.BufferOutput = true;
            //设定输出的字符集
            Response.Charset = "UTF-8";
            //假定导出的文件名为FileName.xls
            Response.AppendHeader("Content-Disposition", "attachment;filename=exportusersinfo.xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //设置导出文件的格式
            Response.ContentType = "application/ms-excel";
            //关闭ViewState
           // EnableViewState = false;
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("zh-cn", true);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
            System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            gv.RenderControl(textWriter);
            //把HTML写回浏览器
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
            Response.Write(stringWriter.ToString());
            Response.End();

            return View();
        }

        public ActionResult Search(string term)
        {
            WebConfigProvider wcp = new WebConfigProvider();
            ICILHelper cil = new CILHelper("", wcp.HRConnectionString);
            CILInfoModel model = new CILInfoModel();
            model.List = cil.GetUserInfoForAutocomplete(term);
            return Json(model.List, JsonRequestBehavior.AllowGet);
        }
    }
}
